package com.whz.generic.utils;

import lombok.experimental.UtilityClass;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Consumer;

/**
 * 有些方法不需要处理异常,这个类有帮助
 *
 * @author whz
 */
@UtilityClass
public class SafeExecutor {

    public boolean execute(Runnable runnable) {
        try {
            if (runnable != null) {
                runnable.run();
            }
            return true;
        } catch (Throwable ignored) {
        }
        return false;
    }

    public <T> T execute(Callable<T> callable) {
        try {
            if (callable != null) {
                return callable.call();
            }
        } catch (Throwable ignored) {
        }
        return null;
    }

    public <T> void consumer(T origin, Consumer<T> consumer) {
        Optional.ofNullable(origin).ifPresent(consumer);
    }

    public <T> void consumerList(Collection<T> origin, Consumer<T> consumer) {
        Optional.ofNullable(origin).ifPresent(o -> o.forEach(consumer));
    }

    public <K, V> void consumerMap(Map<K, V> origin, Consumer<Map.Entry<K, V>> consumer) {
        Optional.ofNullable(origin).ifPresent(o -> o.entrySet().forEach(consumer));
    }
}
